<template>
  <a-modal
    v-model="visible"
    cancelText="取消"
    okText="确定"
    width="50%"
    centered
  >
    <template slot="footer" class="modelBtn">
      <a-button
        @click="visible = false"
        style="background: #d7d7d7; color: #fff; border: none"
        >取消</a-button
      >
      <a-button
        :loading="loading"
        type="primary"
        v-if="modalFlag === 'addNewData'"
        @click="handleOk('addNewData')"
        >确认</a-button
      >
      <a-button
        :loading="loading"
        type="primary"
        v-if="modalFlag === 'edit'"
        @click="handleOk('edit')"
        >确认</a-button
      >
    </template>
    <template slot="title"
      ><span>{{ modalTitle }}</span>
      <span
        :style="
          OutboundModalData.addressVerify
            ? 'margin-left:3rem;color:#3EAE7C;'
            : 'margin-left:3rem;color:red;'
        "
      >
        <span v-if="modalFlag != 'addNewData'">
          {{
            OutboundModalData.addressVerify ? "地址检验通过" : "地址检验不通过"
          }}
        </span>
        <a-button
          v-if="modalFlag != 'addNewData'"
          type="primary"
          size="small"
          @click="checksIte"
          :loading="checksIteLoding"
        >
          重新效验地址
        </a-button>
      </span>
    </template>
    <a-form-model
      ref="ruleForm"
      :model="OutboundModalData"
      :rules="rules"
      layout="inline"
    >
      <h3>基本信息</h3>
      <a-row
        :style="
          modalFlag === 'edit' || modalFlag === 'addNewData'
            ? 'text-align: right'
            : 'text-align: left'
        "
      >
        <a-col class="gutter-row" :span="8">
          <a-form-model-item label="销售平台：" prop="platformId">
            <a-select
              allowClear
              placeholder="请选择销售平台"
              style="width: 10.3rem"
              v-if="modalFlag != 'info'"
              size="small"
              show-search
              option-filter-prop="children"
              :filter-option="filterOption"
              @change="handleChangePlatform"
              v-model="OutboundModalData.platformId"
            >
              <a-select-option
                :value="item.key"
                v-for="item in treeTag"
                :key="item.key"
                :name="item.title"
              >
                {{ item.title }}
              </a-select-option>
            </a-select>
            <span v-else>
              {{
                OutboundModalData.platformName === null ||
                OutboundModalData.platformName === ""
                  ? "暂未选择"
                  : OutboundModalData.platformName
              }}
            </span>
          </a-form-model-item>
        </a-col>
        <a-col class="gutter-row" :span="8">
          <a-form-model-item label="所属店铺：" prop="store">
            <a-select
              allowClear
              placeholder="请选择所属店铺"
              style="width: 10.3rem"
              v-if="modalFlag != 'info'"
              size="small"
              show-search
              option-filter-prop="children"
              :filter-option="filterOption"
              v-model="OutboundModalData.store"
            >
              <a-select-option value="默认" key="默认"> 默认 </a-select-option>
            </a-select>
            <span v-else>
              {{
                OutboundModalData.store === null ||
                OutboundModalData.store === ""
                  ? "暂未选择"
                  : OutboundModalData.store
              }}
            </span>
          </a-form-model-item>
        </a-col>
        <a-col class="gutter-row" :span="8">
          <a-form-model-item label="出库仓库：" prop="warehouseId">
            <a-select
              allowClear
              placeholder="请选择出库仓库"
              style="width: 10.3rem"
              v-if="modalFlag != 'info'"
              size="small"
              show-search
              option-filter-prop="children"
              :filter-option="filterOption"
              @change="handleChangeWarehouse"
              v-model="OutboundModalData.warehouseId"
            >
              <a-select-option
                :value="item.warehouseId"
                v-for="item in clientWareHouse"
                :key="item.warehouseId"
                :name="item.titleName"
              >
                {{ item.titleName }}
              </a-select-option>
            </a-select>
            <span v-else>
              {{
                OutboundModalData.warehouseName === null ||
                OutboundModalData.warehouseName === ""
                  ? "暂未选择"
                  : OutboundModalData.warehouseName
              }}
            </span>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row
        :style="
          modalFlag === 'edit' || modalFlag === 'addNewData'
            ? 'text-align: right'
            : 'text-align: left'
        "
      >
        <a-col class="gutter-row" :span="8">
          <a-form-model-item label="公司名称：" prop="companyName">
            <a-input
              :maxLength="128"
              style="width: 10.3rem"
              placeholder="请输入公司名称"
              v-if="modalFlag != 'info'"
              size="small"
              v-model="OutboundModalData.companyName"
            />
            <span v-else>
              {{
                OutboundModalData.companyName === null ||
                OutboundModalData.companyName === ""
                  ? "暂无"
                  : OutboundModalData.companyName
              }}
            </span>
          </a-form-model-item>
        </a-col>
        <a-col class="gutter-row" :span="8">
          <a-form-model-item label="收件人：" prop="recipient">
            <a-input
              :maxLength="128"
              style="width: 10.3rem"
              placeholder="请输入收件人"
              v-if="modalFlag != 'info'"
              size="small"
              v-model="OutboundModalData.recipient"
            />
            <span v-else>
              {{
                OutboundModalData.recipient === null ||
                OutboundModalData.recipient === ""
                  ? "暂无"
                  : OutboundModalData.recipient
              }}
            </span>
          </a-form-model-item>
        </a-col>
        <a-col class="gutter-row" :span="8">
          <a-form-model-item label="联系电话：" prop="contactPhone">
            <a-input
              :maxLength="128"
              style="width: 10.3rem"
              placeholder="请输入联系电话"
              v-if="modalFlag != 'info'"
              size="small"
              v-model="OutboundModalData.contactPhone"
              @input="
                OutboundModalData.contactPhone =
                  OutboundModalData.contactPhone.replace(/[^\d]/g, '')
              "
            />
            <span v-else>
              {{
                OutboundModalData.contactPhone === null ||
                OutboundModalData.contactPhone === ""
                  ? "暂无"
                  : OutboundModalData.contactPhone
              }}
            </span>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row
        :style="
          modalFlag === 'edit' || modalFlag === 'addNewData'
            ? 'text-align: right'
            : 'text-align: left'
        "
      >
        <a-col class="gutter-row" :span="8">
          <a-form-model-item label="国家：" prop="countryId">
            <a-select
              allowClear
              placeholder="请选择国家"
              style="width: 10.3rem"
              v-if="modalFlag != 'info'"
              size="small"
              show-search
              option-filter-prop="children"
              :filter-option="filterOption"
              @change="handleChangeState"
              v-model="OutboundModalData.countryName"
            >
              <a-select-option
                :value="item.id"
                v-for="item in state"
                :key="item.id"
                :name="item.name"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
            <span v-else>
              {{
                OutboundModalData.countryName === null ||
                OutboundModalData.countryName === ""
                  ? "暂无"
                  : OutboundModalData.countryName
              }}
            </span>
          </a-form-model-item>
        </a-col>
        <a-col class="gutter-row" :span="8">
          <a-form-model-item label="州/市：" prop="provinceId">
            <a-select
              allowClear
              placeholder="请选择州/市"
              style="width: 10.3rem"
              v-if="modalFlag != 'info'"
              size="small"
              show-search
              option-filter-prop="children"
              :filter-option="filterOption"
              @change="handleChangeProvince"
              v-model="OutboundModalData.provinceName"
            >
              <a-select-option
                :value="item.id"
                v-for="item in province"
                :key="item.id"
                :name="item.name"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
            <span v-else>
              {{
                OutboundModalData.provinceName === null ||
                OutboundModalData.provinceName === ""
                  ? "暂无"
                  : OutboundModalData.provinceName
              }}
            </span>
          </a-form-model-item>
        </a-col>
        <a-col class="gutter-row" :span="8">
          <a-form-model-item label="邮编：" prop="postalCode">
            <a-input
              :maxLength="128"
              placeholder="请输入邮编"
              v-if="modalFlag != 'info'"
              size="small"
              style="width: 10.3rem"
              v-model="OutboundModalData.postalCode"
            />
            <span v-else>
              {{
                OutboundModalData.postalCode === null ||
                OutboundModalData.postalCode === ""
                  ? "暂无"
                  : OutboundModalData.postalCode
              }}
            </span>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row
        :style="
          modalFlag != 'edit' && modalFlag != 'addNewData'
            ? 'padding:0'
            : 'padding-left: 1rem'
        "
      >
        <a-col span="24">
          <a-form-model-item style="width: 100%" label="城市名称：" prop="city">
            <a-input
              :maxLength="128"
              placeholder="请输入城市名称"
              style="width: 740px"
              v-if="modalFlag != 'info'"
              size="small"
              v-model.trim="OutboundModalData.city"
            />
            <div v-else style="word-wrap: break-word; word-break: normal;word-break:break-all;">
              {{
                OutboundModalData.city === null || OutboundModalData.city === ""
                  ? "暂无"
                  : OutboundModalData.city
              }}
            </div>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row
        :style="
          modalFlag != 'edit' && modalFlag != 'addNewData'
            ? 'padding:0'
            : 'padding-left: 1rem'
        "
      >
        <a-col span="24">
          <a-form-model-item
            style="width: 100%"
            label="详细地址："
            prop="firstAddress"
          >
            <a-input
              :maxLength="128"
              placeholder="请输入详细地址"
              style="width: 740px"
              v-if="modalFlag != 'info'"
              size="small"
              v-model="OutboundModalData.firstAddress"
            />
            <span v-else style="white-space: normal; word-break: break-all">
              {{
                OutboundModalData.firstAddress === null ||
                OutboundModalData.firstAddress === ""
                  ? "暂无"
                  : OutboundModalData.firstAddress
              }}
            </span>
          </a-form-model-item>
        </a-col>
      </a-row>
      <h3 style="margin-top: 20px">
        添加商品
        <span style="color: #f00; font-size: 14px"
          >(注：请选择仓库后添加SKU)</span
        >
      </h3>
      <div class="add-commodity">
        <p v-if="modalFlag != 'info'" style="padding-left: 1.5rem">
          <span style="margin-right: 20px">
            <span style="color: red; margin: 0">*</span>SKU：<a-select
              placeholder="请选择SKU"
              size="small"
              show-search
              option-filter-prop="children"
              style="width: 15rem"
              :filter-option="filterOption"
              @change="changeAddSku"
              v-model="addTableObj.key"
            >
              <a-select-option
                @click="changeAddSku(item.id, skuOption)"
                :value="item.id"
                v-for="item in SKUchineseName"
                :key="item.id"
                :sku="item.sku"
                :skuname="item.skuName"
                :productTag="item.productTag"
                :remainingNumber="item.remainingNumber"
                :skuId="item.skuId"
                :warehousingId="item.warehousingId"
              >
                {{
                  item.sku +
                  "|" +
                  item.skuName +
                  "*" +
                  "(库存" +
                  item.remainingNumber +
                  ")"
                }}
              </a-select-option>
            </a-select>
          </span>
          <span style="margin-right: 20px">
            <span style="color: red; margin: 0">*</span>
            商品数量：
            {{ addTableObj.inputNumber }}
          </span>
          <span>
            <a-button type="primary" size="small" @click="addSKUTable">
              添加
            </a-button>
          </span>
        </p>
        <a-table
          :columns="columns"
          :data-source="OutboundModalData.recordList"
          :pagination="false"
          bordered
          size="small"
        >
          <span slot="action" slot-scope="text, record">
            <a-popconfirm
              title="确认删除该条数据吗?"
              ok-text="确认"
              cancel-text="取消"
              @confirm="delRows(record)"
            >
              <a
                href="javascript:;"
                :disabled="modalFlag === 'info' ? true : false"
                >删除</a
              >
            </a-popconfirm>
          </span>
        </a-table>
      </div>
      <h3 style="margin-top: 20px">其他信息</h3>
      <a-row
        v-if="!Logistics"
        :style="
          modalFlag === 'edit' || modalFlag === 'info'
            ? 'text-align: left'
            : 'text-align: right'
        "
      >
        <a-col class="gutter-row" :span="8">
          <a-form-model-item label="物流商：" prop="logisticsId">
            <a-select
              placeholder="请选择物流商"
              v-if="modalFlag != 'info'"
              size="small"
              show-search
              option-filter-prop="children"
              style="width: 10.5rem"
              @change="handleChangeLogistics"
              v-model="OutboundModalData.logisticsName"
            >
              <a-select-option
                v-for="item in logisticsArray"
                :value="item.id"
                :key="item.id"
                :logisticsPlatform="item.logisticsPlatform"
                :serviceName="item.serviceName"
                :sysLogisticsId="item.sysLogisticsId"
                :sysLogisticsServiceItemId="item.sysLogisticsServiceItemId"
              >
                <a-tooltip>
                  <template slot="title">
                    {{ item.serviceName }}/{{ item.logisticsPlatform }}
                  </template>
                  {{ item.serviceName }}/{{ item.logisticsPlatform }}
                </a-tooltip>
              </a-select-option>
            </a-select>

            <span v-else>
              {{
                OutboundModalData.logisticsName === null ||
                OutboundModalData.logisticsName === undefined ||
                OutboundModalData.logisticsName === ""
                  ? "暂未选择"
                  : OutboundModalData.logisticsName
              }}
            </span>
          </a-form-model-item>
        </a-col>
        <a-col class="gutter-row" :span="8">
          <a-form-model-item label="预定包裹：" prop="parcel">
            <a-select
              allowClear
              placeholder="请选择预定包裹"
              v-if="modalFlag != 'info'"
              size="small"
              show-search
              option-filter-prop="children"
              style="width: 10.5rem"
              :filter-option="filterOption"
              v-model="OutboundModalData.parcel"
            >
              <a-select-option value="默认" key="默认"> 默认 </a-select-option>
            </a-select>
            <span v-else>
              {{
                OutboundModalData.parcel === undefined ||
                OutboundModalData.parcel === ""
                  ? "暂未选择"
                  : OutboundModalData.parcel
              }}
            </span>
          </a-form-model-item>
        </a-col>
        <a-col class="gutter-row" :span="8">
          <a-form-model-item label="保险保额：" prop="insuredAmount">
            <a-input
              :maxLength="128"
              placeholder="请输入保险保额"
              v-if="modalFlag != 'info'"
              size="small"
              style="width: 10.5rem"
              v-model="OutboundModalData.insuredAmount"
            />
            <span v-else>
              {{
                OutboundModalData.insuredAmount === null ||
                OutboundModalData.insuredAmount === ""
                  ? "暂无"
                  : OutboundModalData.insuredAmount
              }}
            </span>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row
        :style="
          modalFlag === 'edit' || modalFlag === 'info'
            ? 'padding:0'
            : 'padding-left: 1.8rem'
        "
      >
        <a-col span="24">
          <a-form-model-item label="签收选择：" prop="as">
            <a-checkbox
              v-model="signFlag"
              @change="onChangeSign"
              :disabled="modalFlag === 'info' ? true : false"
            >
              签收服务(将按物流商生产签收费用)
            </a-checkbox>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row
        :style="
          modalFlag === 'edit' || modalFlag === 'info'
            ? 'text-align: left'
            : 'text-align: right'
        "
      >
        <a-col class="gutter-row" :span="24"> </a-col>
      </a-row>
      <a-row
        :style="
          modalFlag === 'edit' || modalFlag === 'info'
            ? 'padding:0'
            : 'padding-left: 1.8rem'
        "
      >
        <a-col class="gutter-row" :span="16">
          <a-form-model-item label=" 物流运单：" prop="insuredAmount">
            <a-checkbox
              @change="onChangeLogistics"
              v-model="Logistics"
              :disabled="modalFlag === 'info' ? true : false"
            >
              自有物流运单(需要自己上传物流派送运单文件才可提交仓库处理)
            </a-checkbox>
          </a-form-model-item>
        </a-col>
        <a-col class="gutter-row" :span="8" style="text-align: right"> </a-col>
      </a-row>
      <a-row
        :style="
          modalFlag === 'edit' || modalFlag === 'info'
            ? 'padding:0'
            : 'padding-left: 1.8rem'
        "
        v-if="Logistics"
      >
        <a-col span="24"> </a-col>
      </a-row>
      <h3 v-if="Logistics" style="margin-top: 20px">包裹信息</h3>
      <a-table
        v-if="Logistics"
        :columns="parcelInfoColumns"
        :data-source="OutboundModalDataArry"
        :pagination="false"
        bordered
        size="small"
      >
        <!-- 包裹 -->
        <span slot="boxSize">
          {{
            OutboundModalData.lengthNumber === null ||
            OutboundModalData.lengthNumber === undefined
              ? 0
              : OutboundModalData.lengthNumber
          }}*{{
            OutboundModalData.widthNumber === null ||
            OutboundModalData.widthNumber === undefined
              ? 0
              : OutboundModalData.widthNumber
          }}*{{
            OutboundModalData.heightNumber === null ||
            OutboundModalData.heightNumber === undefined
              ? 0
              : OutboundModalData.heightNumber
          }}(cm)<br />
          {{
            OutboundModalData.weightNumber === null ||
            OutboundModalData.weightNumber === undefined
              ? 0
              : OutboundModalData.weightNumber
          }}(g)
        </span>
        <!-- 物流商 -->
        <span slot="logisticsId" class="table-logisticsId">
          <a-form-model-item prop="logisticsId">
            <a-select
              placeholder="请选择物流商"
              v-if="modalFlag != 'info'"
              size="small"
              show-search
              option-filter-prop="children"
              style="width: 10.5rem"
              @change="handleChangeLogistics"
              v-model="OutboundModalData.logisticsName"
            >
              <a-select-option
                v-for="item in logisticsArray"
                :value="item.id"
                :key="item.id"
                :logisticsPlatform="item.logisticsPlatform"
                :serviceName="item.serviceName"
                :sysLogisticsId="item.sysLogisticsId"
                :sysLogisticsServiceItemId="item.sysLogisticsServiceItemId"
              >
                <a-tooltip>
                  <template slot="title">
                    {{ item.serviceName }}/{{ item.logisticsPlatform }}
                  </template>
                  {{ item.serviceName }}/{{ item.logisticsPlatform }}
                </a-tooltip>
              </a-select-option>
            </a-select>
            <span v-else>
              {{ OutboundModalData.logisticsName }}
            </span>
          </a-form-model-item>
        </span>
        <!-- 物流方式 -->
        <span slot="logisticsService">
          <a-form-model-item prop="logisticsService" class="logistics">
            <a-select
              v-if="modalFlag != 'info'"
              size="small"
              show-search
              option-filter-prop="children"
              style="width: 7rem"
              v-model="OutboundModalData.logisticsService"
              @change="changeLogisticsServiceArry"
            >
              <a-select-option
                v-for="item in logisticsServiceArry"
                :value="item.wayName"
                :sysLogisticsServiceWayTenantId="
                  item.sysLogisticsServiceWayTenantId
                "
                :key="item.sysLogisticsServiceWayTenantId"
              >
                {{ item.wayName }}
              </a-select-option>
            </a-select>
            <span v-else>
              {{ OutboundModalData.logisticsService }}
            </span>
          </a-form-model-item>
        </span>
        <!-- 物流单号 -->
        <span slot="ectnNo">
          <a-form-model-item prop="ectnNo" class="logistics">
            <a-input
              :maxLength="128"
              style="width: 5rem"
              v-if="modalFlag != 'info'"
              size="small"
              v-model="OutboundModalData.ectnNo"
            />
            <span v-else>
              {{ OutboundModalData.ectnNo }}
            </span>
          </a-form-model-item>
        </span>
        <!-- 运单文件 -->
        <span slot="ectnFile">
          <a-upload
            :beforeUpload="beforeUploads"
            v-if="imgUrl === '' || imgUrl === null || imgUrl === undefined"
            :action="baseUrl + '/by-file/uploadFile'"
            name="file"
            :file-list="fileList"
            :headers="headersRow"
            :multiple="true"
            @preview="handlePreview"
            @change="(fileList) => handleChangeRow(fileList)"
          >
            <a-button v-if="fileList.length < 1" type="primary" size="small">
              <a-icon type="upload" /> 上传文件
            </a-button>
          </a-upload>
          <span v-if="imgUrl">
            <a :href="imgUrl" target="_blank">查看跟踪运单文件</a>
            <a-icon
              type="delete"
              style="cursor: pointer"
              @click="delFile"
              v-if="modalFlag === 'addNewData' || modalFlag === 'edit'"
            />
          </span>
        </span>
        <!-- 物流费用-->
        <span slot="logisticsCost">
          <a-form-model-item prop="logisticsCost" class="logistics">
            <a-input-number
              style="width: 5rem"
              v-if="modalFlag != 'info'"
              size="small"
              v-model="OutboundModalData.logisticsCost"
              :min="0"
            />
            <span v-else>
              {{ OutboundModalData.logisticsCost }}
            </span>
          </a-form-model-item>
        </span>
      </a-table>
      <h3 style="margin-top: 20px">备注信息</h3>
      <div class="remark">
        <span v-if="modalFlag === 'info'">{{ OutboundModalData.remark }}</span>
        <a-textarea
          :maxLength="256"
          v-if="modalFlag != 'info'"
          :rows="1"
          v-model="OutboundModalData.remark"
        />
        <span v-else>
          {{
            OutboundModalData.remark === null || OutboundModalData.remark === ""
              ? "暂无"
              : OutboundModalData.remark
          }}
        </span>
      </div>
      <a-modal
        v-model="skuVisible"
        :title="SKUTitle"
        @ok="skuOk"
        width="40%"
        okText="提交"
      >
        <a-table
          :columns="skuColumns"
          :data-source="skuDataSource"
          size="small"
          bordered
          :rowSelection="{
            onSelect: onSelect,
            onSelectAll: onSelectAll,
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
          }"
        >
          <span slot="inputNumber" slot-scope="text, record">
            <a-input-number
              size="small"
              v-model="record.inputNumber"
              :min="0"
              :max="record.remainingNumber * 1"
            />
          </span>
        </a-table>
      </a-modal>
    </a-form-model>
    <h3
      v-if="
        (OutboundKeys === '25' || OutboundKeys === '35') &&
        modalFlag != 'addNewData'
      "
      style="margin-top: 20px"
    >
      服务项
    </h3>
    <div
      v-if="
        (OutboundKeys === '25' || OutboundKeys === '35') &&
        modalFlag != 'addNewData'
      "
    >
      <a-button size="small" type="primary" @click="costServiceInfo">
        服务项登记查看
      </a-button>
    </div>
    <!-- 服务项信息查看 -->
    <ServiceModalReap />
  </a-modal>
</template>

<script>
import ServiceModalReap from "@/components/serviceModal/ServiceModalReap.vue";
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
import { mapState } from "vuex";
import {
  Outbound_state,
  Outbound_Province,
  Outbound_treeTag,
  Outbound_Add,
  Outbound_rowInfo,
  Outbound_edit,
  Outbounddel_housPdt,
  Outbounddel_pageBpi,
  // Outbounddel_carrierServe,
  // Outbounddel_carrier,
  updateRecord,
} from "@/apis/clientSide/OrderManage/Outbound";
import { OutBound_addressVerify } from "@/apis/system/WM/OutOrder";
import { removefile, selectTenantIdAllServerName } from "@/apis/common";
import baseUrl from "@/utils/baseUrl";
export default {
  props: ["getOutboundTableList", "getStateCount", "OutboundKeys"],
  components: {
    ServiceModalReap,
  },
  created() {
    this.getState();
    this.getWarehouseList();
  },
  data() {
    return {
      skuOption: {},
      checksIteLoding: false,
      // 仓库ID
      warehouseID: "",

      parcelInfoData: [],
      // SKU分页
      skuPage: {
        size: 1,
        current: 1,
      },
      // SKU选择框
      selectionRowsPlus: [],
      // SKU选择框数据
      selectedRowKeys: [],
      // SKU库存表格数据
      skuDataSource: [],
      //sku选择模态框TITLE
      SKUTitle: "",
      // 选择SKU模态框
      skuVisible: false,
      // 物流方式费用
      logisticsServiceArry: [],
      //验证规则
      rules: {
        platformId: [
          { required: true, message: "请选择销售平台", trigger: "blur" },
        ],
        warehouseId: [
          { required: true, message: "请选择出库仓库", trigger: "blur" },
        ],
        recipient: [
          { required: true, message: "请输入收件人", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "长度限制为3-20位",
            trigger: "blur",
          },
        ],
        contactPhone: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
          {
            min: 10,
            max: 20,
            message: "长度限制为10-20位",
            trigger: "blur",
          },
        ],
        countryId: [{ required: true, message: "请选择国家", trigger: "blur" }],
        provinceId: [
          { required: true, message: "请选择州/市", trigger: "blur" },
        ],
        postalCode: [
          { required: true, message: "请输入邮编", trigger: "blur" },
        ],
        firstAddress: [
          { required: true, message: "请输入详细地址", trigger: "blur" },
        ],
        ectnNo: [
          { required: true, validator: this.checkEctnNo, trigger: "blur" },
        ],
        logisticsCost: [
          {
            required: true,
            validator: this.checkLogisticsCost,
            trigger: "blur",
          },
        ],
        logisticsId: [
          {
            required: false,
            validator: this.checkLogisticsId,
            trigger: "blur",
          },
        ],
        logisticsService: [
          { validator: this.checkLogisticsService, trigger: "blur" },
        ],
        city: [{ required: true, message: "请输入城市名称", trigger: "blur" }],
      },
      //修改标杆
      edit: false,
      loading: false,
      iconFlag: false,
      // 上传标杆
      imgUrl: "",
      uploadImgFlag: false,
      baseUrl,
      fileList: [],
      previewImage: "",
      previewVisible: false,
      //上传文件请求头
      headersRow: {
        authorization: "authorization-text",
        token: sessionStorage.getItem("tk"),
      },
      modalTitle: "",
      //模态框提交标杆
      modalFlag: "",
      //sku列表
      SKUchineseName: [],
      //销售平台
      treeTag: [],
      // 国家
      state: [],
      //   省市区
      province: [],
      // 签收服务标杆
      signFlag: false,
      // 物流运单标杆
      Logistics: false,
      visible: false,
      //sku库存数量
      remainingNumber: "",
      // SKUid
      addTableObj: {
        //输入数量
        inputNumber: 0,
        // Id
        id: "",
        // SKU名称
        skuName: "",
        //   // SKU标签
        productTag: "",
        //   // sku
        sku: "",
        key: undefined,
        skuId: "",
      },
      //包裹信息表格数
      OutboundModalDataArry: [],
      OutboundModalData: {
        lengthNumber: null,
        heightNumber: null,
        widthNumber: null,
        weightNumber: null,
        // //   状态
        // applyState: 0,
        // 批次号
        batchNo: "",
        // 公司名称
        companyName: "",
        // 联系电话
        contactPhone: "",
        // 国家ID
        countryId: undefined,
        //  国家名称
        countryName: "",
        //  创建人
        createBy: 0,
        // 创建时间
        createTime: "",
        // 跟踪文件
        ectnFile: "",
        // 跟踪单号
        ectnNo: "",
        // 邮箱
        email: "",
        // 详细地址1
        firstAddress: "",
        // id: 0,
        // 保险保额
        insuredAmount: 0,
        // 0:未选择自有运单 1：已选择自有运单
        isEctn: 0,
        // 物流商_id
        logisticsId: undefined,
        // 物流商名称
        logisticsName: "",
        // 0:正常订单 1：复合订单
        orderCode: 0,
        // 订单编号
        orderNumber: "",
        // 订单价格
        orderPrice: "",
        // 预定包裹
        parcel: undefined,
        // 销售平台ID
        platformId: undefined,
        // 销售平台名称
        platformName: "",
        // 邮编
        postalCode: "",
        recordList: [
          // {
          //   // 输入数量
          //   inputNumber: 0,
          //   // Id
          //   id: "",
          //   // SKU名称
          //   skuName: "",
          //   // SKU标签
          //   productTag: "",
          //   // sku
          //   sku: "",
          // },
        ],
        city: "",
        // 地区ID
        provinceId: undefined,
        // 地区名称
        provinceName: "",
        // 收件人
        recipient: "",
        // 库存数量
        remainingNumber: 0,
        // 备注
        remark: "",
        // revision: 0,
        // 详细地址二
        secondAddress: "",
        // 签收选择
        sign: 0,
        // 店铺
        store: undefined,
        // // 所属公司ID
        // tenantId: 0,
        // 更新时间
        updateTime: "",
        // 仓库ID
        warehouseId: undefined,
        // 仓库名称
        warehouseName: "",
        logisticsService: null,
        logisticsCost: null,
      },
      modalKey: "",
      modalEditFlag: "",
      flagArry: [],
    };
  },
  mounted() {
    this.editRow();
    this.$bus.$off("showOutboundAddModal");
    this.$bus.$on("showOutboundAddModal", () => {
      for (let key in this.OutboundModalData) {
        this.OutboundModalData[key] = undefined;
      }
      this.OutboundModalDataArry = [];
      this.modalTitle = "新建出库订单";
      this.modalFlag = "addNewData";
      this.addTableObj.key = undefined;
      this.Logistics = false;
      this.signFlag = false;
      this.OutboundModalData.recordList = [];
      this.visible = true;
      this.fileList = [];
      this.imgUrl = "";
      this.edit = false;
      this.OutboundModalDataArry.push(this.OutboundModalData);
    });
  },
  methods: {
    //费用服务项信息查看
    costServiceInfo() {
      setTimeout(() => {
        this.$bus.$emit(
          "reappearance",
          this.OutboundModalData,
          3,
          this.OutboundModalData.key
        );
      }, 50);
    },
    //检查地址
    checksIte() {
      this.checksIteLoding = true;
      setTimeout(async () => {
        let { code } = await OutBound_addressVerify(this.OutboundModalData.key);
        if (code === "10000") {
          this.getModalData(this.modalKey);
          this.checksIteLoding = false;
        } else {
          this.checksIteLoding = false;
        }
      }, 1000);
    },
    // SKU模态框选择复选框
    onSelect(record, selected) {
      selected
        ? this.selectionRowsPlus.push(record)
        : this.selectionRowsPlus.splice(
            this.selectionRowsPlus.findIndex((x) => x.id === record.id),
            1
          );
    },
    onSelectAll(selected, selectedRows, changeRows) {
      this.selectionRowsPlus = selected
        ? this.selectionRowsPlus.concat(changeRows)
        : this.selectionRowsPlus.filter(
            (x) => !changeRows.find((i) => i.id === x.id)
          );
    },
    // 选中
    onSelectChange(selectedRowKeys) {
      this.$nextTick(() => {
        this.selectedRowKeys = selectedRowKeys;
      });
    },
    //sku提交
    skuOk() {
      let flag = true;
      if (this.selectionRowsPlus.length <= 0) {
        this.$message.error("请选择SKU后提交！");
        return false;
      }

      if (this.selectionRowsPlus.length >= 1) {
        this.selectionRowsPlus.forEach((item) => {
          if (item.inputNumber * 1 === 0) {
            flag = false;
            this.$message.error("选择的SKU出库数量不能为0！");
            return false;
          }

          this.OutboundModalData.recordList.forEach((item) => {
            if (this.addTableObj.sku === item.sku) {
              this.$message.error("修改重复数据时，请先删除！");
              flag = false;
              return false;
            }
          });
        });
      }

      if (flag) {
        this.addTableObj.inputNumber = 0;
        this.selectionRowsPlus.forEach((item) => {
          this.addTableObj.inputNumber += item.inputNumber * 1;
          this.addTableObj.prList = this.selectionRowsPlus;
          this.skuVisible = false;
        });
      }
    },
    // 验证运单号
    checkEctnNo(rule, value, callback) {
      if (this.Logistics) {
        if (value != "" && value != null && value != undefined) {
          callback();
        } else {
          callback(new Error("运单号不能为空！"));
        }
      }
    },
    // 验证物流费用
    checkLogisticsCost(rule, value, callback) {
      if (this.Logistics) {
        if (value != "" && value != null && value != undefined && value != 0) {
          callback();
        } else {
          callback(new Error("物流费不能为空或为0！"));
        }
      }
    },
    // 验证物流商
    checkLogisticsId(rule, value, callback) {
      if (this.Logistics) {
        if (value != "" && value != null && value != undefined && value != 0) {
          callback();
        } else {
          callback(new Error("物流商不能为空！"));
        }
      } else {
        if (
          this.OutboundModalData.recordList[0].inputNumber * 1 === 1 &&
          this.OutboundModalData.recordList.length === 1 &&
          this.OutboundModalData.recordList[0].prList[0].inputNumber * 1 === 1
        ) {
          if (
            value != "" &&
            value != null &&
            value != undefined &&
            value != 0
          ) {
            callback();
          } else {
            callback(new Error("普通订单，物流商为必填项！"));
          }
        } else {
          callback();
        }
      }
    },
    // 验证物流方式
    checkLogisticsService(rule, value, callback) {
      if (this.Logistics) {
        if (this.OutboundModalData.logisticsId != "1") {
          if (
            value != "" &&
            value != null &&
            value != undefined &&
            value != 0
          ) {
            callback();
          } else {
            callback(new Error("物流方式不能为空！"));
          }
        } else {
          callback();
        }
      } else {
        callback();
      }
    },
    //删除图片
    async delFile() {
      if (this.imgUrl != "") {
        let { code } = await removefile(this.imgUrl.split(","));
        if (code === "10000") {
          this.imgUrl = "";
          this.OutboundModalData.ectnFile = "";
        }
      }
    },
    // 限制上传文件
    beforeUploads(file) {
      return new Promise((resolve, reject) => {
        this.files = file;
        const pdf = file.type === "application/pdf";
        const isLt6M = file.size / 1024 / 1024 < 6;
        const img =
          file.type === "image/jpeg" ||
          file.type === "image/png" ||
          file.type === "image/jpg";
        if (!pdf && !img) {
          this.$message.error("上传文件只能是 png、jpeg、jpg、PDF!");
          return reject(false);
        }
        if (!isLt6M) {
          this.$message.error("文件大小限制小于6MB!");
          return reject(false);
        }
        return resolve(true);
      });
    },
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    //每一行上传文件
    async handleChangeRow(info) {
      this.fileList = info.fileList;
      if (info.file.status === "done") {
        this.$message.success(`${info.file.name} 上传成功`);
        this.OutboundModalData.ectnFile =
          info.file.response.responseBody.join(",");
      } else if (info.file.status === "removed") {
        let res = await removefile(info.file.response.responseBody);
        res;
      }
    },
    //单箱删除行
    delRows(record) {
      if (this.edit === true) {
        if (this.flagArry.length <= 0) {
          this.OutboundModalData.recordList.forEach(async (item, i) => {
            if (record.key === item.key) {
              this.OutboundModalData.recordList.splice(i, 1);
              this.$message.success("删除成功");
            }
          });
        } else {
          this.flagArry.forEach(async (item) => {
            if (record.key === item.key) {
              let { code } = await updateRecord(record.key);
              if (code === "10000") {
                this.OutboundModalData.recordList.forEach(async (item, i) => {
                  if (record.key === item.key) {
                    this.OutboundModalData.recordList.splice(i, 1);
                    this.getOutboundTableList();
                  }
                });
              }
            } else {
              this.OutboundModalData.recordList.forEach(async (item, i) => {
                if (record.key === item.key) {
                  this.OutboundModalData.recordList.splice(i, 1);
                  this.$message.success("删除成功");
                }
              });
            }
          });
        }
      } else if (this.edit === false) {
        this.OutboundModalData.recordList.forEach((item, i) => {
          if (record.key === item.key) {
            this.OutboundModalData.recordList.splice(i, 1);
            this.$message.success("删除成功");
          }
        });
      }
    },
    //添加数据到表格
    addSKUTable() {
      if (this.addTableObj.inputNumber === 0) {
        this.$message.error("SKU数量不能0,请填写SKU数量后提交");
        return false;
      }
      if (
        this.selectionRowsPlus.length >= 1 &&
        this.OutboundModalData.recordList.length === 0
      ) {
        this.OutboundModalData.recordList.push({
          skuName: this.addTableObj.skuName,
          sku: this.addTableObj.sku,
          productTag: this.addTableObj.productTag,
          inputNumber: this.addTableObj.inputNumber,
          productId: this.addTableObj.key,
          skuId: this.addTableObj.skuId,
          prList: this.addTableObj.prList,
          warehousingId: this.addTableObj.warehousingId,
        });
      } else {
        if (this.OutboundModalData.recordList.length >= 1) {
          this.OutboundModalData.recordList.forEach((item, i) => {
            if (item.sku === this.addTableObj.sku) {
              this.OutboundModalData.recordList.splice(i, 1);
            }
          });
          this.OutboundModalData.recordList.push({
            skuName: this.addTableObj.skuName,
            sku: this.addTableObj.sku,
            productTag: this.addTableObj.productTag,
            inputNumber: this.addTableObj.inputNumber,
            productId: this.addTableObj.key,
            skuId: this.addTableObj.skuId,
            prList: this.addTableObj.prList,
            warehousingId: this.addTableObj.warehousingId,
          });
        }
      }

      this.addTableObj.inputNumber = 0;
      this.selectionRowsPlus = [];
      this.selectedRowKeys = [];
    },
    //点击提交或修改
    handleOk(flag) {
      this.loading = true;
      if (this.Logistics) {
        if (
          this.OutboundModalData.ectnFile === null ||
          this.OutboundModalData.ectnFile === "" ||
          this.OutboundModalData.ectnFile === undefined
        ) {
          this.$message.error("勾选物流后必须上传文件！");
          this.loading = false;
          return false;
        }
      }

      if (this.OutboundModalData.recordList.length <= 0) {
        this.$message.error("请添加商品SKU数量！");
        this.loading = false;
        return false;
      }
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (flag === "addNewData") {
            setTimeout(async () => {
              let { code } = await Outbound_Add(this.OutboundModalData);
              if (code === "10000") {
                this.getOutboundTableList();
                this.getStateCount();
                this.visible = false;
                this.loading = false;
              } else {
                this.loading = false;
              }
            }, 1000);
          } else if (flag === "edit") {
            setTimeout(async () => {
              let { code } = await Outbound_edit(this.OutboundModalData);
              if (code === "10000") {
                this.getOutboundTableList();
                this.visible = false;
                this.loading = false;
              } else {
                this.loading = false;
              }
            }, 1000);
          }
        } else {
          this.loading = false;
          this.$message.error("缺少必填项，请填写后提交！");

          return false;
        }
      });
    },
    // 销售平台更改
    handleChangePlatform(value, option) {
      this.OutboundModalData.platformName = option.data.attrs.name;
      // this.OutboundModalData.platformId = value * 1;
    },
    // 出库仓库更改
    async handleChangeWarehouse(value, option) {
      let { code, responseBody } = await Outbounddel_housPdt(value);
      if (code === "200") {
        this.SKUchineseName = responseBody;
      }
      this.addTableObj.key = undefined;
      this.OutboundModalData.recordList = [];
      this.addTableObj.inputNumber = 0;
      this.OutboundModalData.warehouseName = option.data.attrs.name;
      // this.OutboundModalData.warehouseId = value * 1;
    },
    // 地区更改
    handleChangeProvince(value, option) {
      this.OutboundModalData.provinceName = option.data.attrs.name;
      this.OutboundModalData.provinceId = value;
    },
    // 物流商更改
    async handleChangeLogistics(value, option) {
      this.OutboundModalData.logisticsName =
        option.data.attrs.serviceName +
        "/" +
        option.data.attrs.logisticsPlatform;
      this.OutboundModalData.logisticsId =
        option.data.attrs.sysLogisticsId +
        "," +
        option.data.attrs.sysLogisticsServiceItemId;
      let { code, responseBody } = await selectTenantIdAllServerName(
        option.data.attrs.sysLogisticsId,
        option.data.attrs.sysLogisticsServiceItemId,
        sessionStorage.getItem("tenantId")
      );
      if (code === "200") {
        this.logisticsServiceArry = responseBody;
        this.OutboundModalData.logisticsService = null;
      }
    },
    //物流方式更改
    changeLogisticsServiceArry(value, option) {
      this.OutboundModalData.logisticsService = value;
      this.OutboundModalData.logisticsServiceId =
        option.data.attrs.sysLogisticsServiceWayTenantId;
    },

    //签收选择
    onChangeSign(e) {
      this.signFlag = e.target.checked;
      this.OutboundModalData.sign = e.target.checked ? 1 : 0;
    },
    // 物流运单
    onChangeLogistics(e) {
      this.Logistics = e.target.checked;
      this.OutboundModalData.isEctn = e.target.checked ? 1 : 0;
      if (!e.target.checked) {
        this.delFile();
        this.OutboundModalData.logisticsId = null;
        this.OutboundModalData.logisticsService = null;
        this.OutboundModalData.ectnNo = null;
        this.OutboundModalData.logisticsCost = null;
      }
    },
    // 添加SKU下拉框
    async changeAddSku(value, option) {
      this.skuVisible = true;
      this.skuOption = { ...option };
      let { code, responseBody } = await Outbounddel_pageBpi({
        stockId: value,
        size: this.skuPage.size,
        current: this.skuPage.current,
      });
      if (code === "200") {
        responseBody.records.forEach((item) => {
          item.createTime = item.createTime.replace("T", "   ");
        });
        this.skuDataSource = responseBody.records;
      }
      //数量回显
      if (this.OutboundModalData.recordList.length >= 1) {
        this.OutboundModalData.recordList.forEach((item) => {
          item.prList.forEach((v) => {
            this.skuDataSource.forEach((v2, i) => {
              if (v.key === v2.key)
                this.skuDataSource[i].inputNumber = v.inputNumber;
            });
          });
        });
      }

      this.SKUTitle = this.skuOption.data.attrs.sku;
      this.addTableObj.skuName = this.skuOption.data.attrs.skuname;
      this.addTableObj.sku = this.skuOption.data.attrs.sku;
      this.addTableObj.skuId = this.skuOption.data.attrs.skuId;
      this.addTableObj.productTag = this.skuOption.data.attrs.productTag;
      this.addTableObj.warehousingId = this.skuOption.data.attrs.warehousingId;
      this.remainingNumber = this.skuOption.data.attrs.remainingNumber;
    },
    // 国家下拉
    async handleChangeState(value, option) {
      this.OutboundModalData.provinceName = undefined;
      this.OutboundModalData.provinceId = undefined;
      this.OutboundModalData.countryName = option.data.attrs.name;
      this.OutboundModalData.countryId = value;
      let { code, responseBody } = await Outbound_Province(option.data.key);
      if (code === "200") {
        this.province = responseBody;
      }
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    //获取国家接口
    async getState() {
      let { code, responseBody } = await Outbound_state();
      if (code === "200") {
        this.state = responseBody;
      }
    },
    //获取仓库列表 获取销售平台  物流商
    async getWarehouseList() {
      let res = await Outbound_treeTag({
        tagType: 6,
      });
      if (res.code === "200") {
        this.treeTag = res.responseBody;
      }
    },
    //修改每一行数据
    editRow() {
      this.$bus.$off("OutboundRowData");
      this.$bus.$on("OutboundRowData", async (rowData, flag) => {
        this.addTableObj.key = undefined;
        this.modalKey = rowData.key;
        this.modalEditFlag = flag;
        this.getModalData(rowData.key, flag);
        this.OutboundModalDataArry = [];
      });
    },
    //获取模态框数据
    async getModalData(key, flag) {
      let { code, responseBody } = await Outbound_rowInfo(key);
      if (code === "200") {
        this.flagArry = [...responseBody.recordList];
        this.OutboundModalData = { ...responseBody };
        this.Logistics = this.OutboundModalData.isEctn === "1" ? true : false;
        this.signFlag = this.OutboundModalData.sign === "1" ? true : false;
        let res = await Outbound_Province(this.OutboundModalData.countryId);
        if (res.code === "200") {
          this.province = res.responseBody;
        }
        if (this.OutboundModalData.isEctn === "0") {
          this.imgUrl = "";
          this.previewImage = "";
        } else {
          this.imgUrl = this.OutboundModalData.ectnFile;
          this.previewImage = this.OutboundModalData.ectnFile;
          this.fileList = [];
        }
      }
      this.OutboundModalDataArry.push(this.OutboundModalData);
      this.warehouseID = responseBody.warehouseId;
      let res = await Outbounddel_housPdt(this.warehouseID);
      if (res.code === "200") {
        this.SKUchineseName = res.responseBody;
      }
      if (flag === "edit") {
        this.modalTitle = "修改出库订单";
        this.modalFlag = "edit";
        this.visible = true;
        this.edit = true;
      } else if (flag === "info") {
        this.modalTitle = "查看出库订单详情";
        this.modalFlag = "info";
        this.visible = true;
      }
    },
  },
  computed: {
    ...mapState(["clientWareHouse"]),
    ...mapState(["logisticsArray"]),
    columns() {
      return [
        {
          title: "商品名称",
          dataIndex: "skuName",
          align: "center",
          // scopedSlots: { customRender: "selfClassifyName" },
          ellipsis: true,
          width: "20%",
        },
        {
          title: "SKU",
          dataIndex: "sku",
          align: "center",
          width: "20%",
          ellipsis: true,
          scopedSlots: { customRender: "sku" },
        },
        {
          title: "标签",
          dataIndex: "productTag",
          scopedSlots: { customRender: "productTag" },
          align: "center",
          width: "20%",
          ellipsis: true,
        },
        {
          title: "数量",
          dataIndex: "inputNumber",
          scopedSlots: { customRender: "inputNumber" },
          align: "center",
          width: "20%",
          ellipsis: true,
        },
        {
          title: "操作",
          dataIndex: "action",
          scopedSlots: { customRender: "action" },
          align: "center",
          width: 120,
        },
      ];
    },
    skuColumns() {
      return [
        {
          title: "箱子编号",
          dataIndex: "boxNumber",
          key: "boxNumber",
        },
        {
          title: "入库时间",
          dataIndex: "createTime",
          key: "createTime",
          scopedSlots: { customRender: "createTime" },
        },
        {
          title: "剩余库存",
          dataIndex: "remainingNumber",
          key: "remainingNumber",
        },
        {
          title: "出库数量",
          key: "inputNumber",
          dataIndex: "inputNumber",
          scopedSlots: { customRender: "inputNumber" },
        },
      ];
    },
    parcelInfoColumns() {
      return [
        {
          align: "center",
          title: "包裹",
          dataIndex: "boxSize",
          key: "boxSize",
          scopedSlots: { customRender: "boxSize" },
        },
        {
          align: "center",
          title: "物流商",
          dataIndex: "logisticsId",
          key: "logisticsId",
          scopedSlots: { customRender: "logisticsId" },
        },
        {
          align: "center",
          title: "物流方式",
          dataIndex: "logisticsService",
          key: "logisticsService",
          scopedSlots: { customRender: "logisticsService" },
        },
        {
          align: "center",
          title: "物流单号 ",
          key: "ectnNo",
          dataIndex: "ectnNo",
          scopedSlots: { customRender: "ectnNo" },
        },
        {
          align: "center",
          title: "运单文件",
          key: "ectnFile",
          dataIndex: "ectnFile",
          scopedSlots: { customRender: "ectnFile" },
        },
        {
          align: "center",
          title: "物流费用 ",
          key: "logisticsCost",
          dataIndex: "logisticsCost",
          scopedSlots: { customRender: "logisticsCost" },
        },
      ];
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.ant-form-inline .ant-form-item-with-help {
  margin-bottom: 0 !important;
}
.ant-col-7 {
  line-height: 40px;
}
/deep/.ant-form-explain {
  text-align: left !important;
}
/deep/.ant-upload.ant-upload-select-picture-card {
  height: 40px !important;
  margin: 0;
}
/deep/.ant-empty-normal {
  margin: 0px !important;
}
/deep/.ant-modal-footer {
  text-align: center !important;
  button {
    margin: 0 50px;
  }
}
</style>